import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.activation.MimetypesFileTypeMap;
import org.apache.commons.fileupload.util.Streams;

import javax.naming.NamingException;

import unilearn.domain.*;
import unilearn.facade.*;

/**
 * @author Yin Zhang, 5393558
 * @version 0.1, 07 May 2008, initial creation
 */
public class StaffUserStory2
{
	private static PrintWriter fileOutput = null;
	private static final String OUTPUTPATH = "staffUserStory2";
	private static final String OUTPUTFILENAME = "staffDownloadSubmissions.txt";
	
	public StaffUserStory2() throws FileNotFoundException, IOException
	{
		File filePath = new File(OUTPUTPATH);
		
		if(!filePath.exists())
		{
			filePath.mkdir();
		}
		
		fileOutput = new PrintWriter(new FileOutputStream(OUTPUTPATH + File.separator + OUTPUTFILENAME));
	}
	
	public void uploadAssignment(String staffID, String fileName) throws SQLException, NamingException, IOException
	{
		DataFile assignmentFile = new DataFile();
		assignmentFile.setFileName(fileName);
		File temp = new File(fileName);
		if(temp.exists())
		{
			assignmentFile.setFileSize(temp.length());
			assignmentFile.setFile(temp);
			assignmentFile.setFileType(new MimetypesFileTypeMap().getContentType(temp));
			long fileID = FileFacade.insertFile(assignmentFile);
			temp.delete();
			downloadAssignment(staffID, fileID);
		}
	}
	
	private void downloadAssignment(String staffID, long fileID) throws SQLException, NamingException, IOException
	{
		DataFile assignmentFile = FileFacade.getFileByID(fileID);
		File temp = assignmentFile.getFile();
		FileInputStream inStream = new FileInputStream(temp);
		String fileName = assignmentFile.getFileName();
		FileOutputStream outStream = new FileOutputStream(OUTPUTPATH + File.separator + fileName);
		Streams.copy(inStream, outStream, true);
		temp.delete();
		inStream.close();
		outStream.close();
		
		fileOutput.println("File Name: " + fileName);
		fileOutput.println("File Type: " + assignmentFile.getFileType());
		fileOutput.println("File Size: " + assignmentFile.getFileSize());
		fileOutput.println("Download By: " + staffID);
	}

	public void close()
	{
		try
		{
			fileOutput.close();
		}
		finally
		{
			fileOutput = null;
		}
	}
}